import React, { useState, useRef, useEffect } from "react";
import { Modal, Form, Input, Spin } from "antd";

const AddDepartment = ({ dep, open, onOk, onCancel }) => {
  // 克隆部门信息
  const [addingDep, setAddingDep] = useState({ ...dep });
  const [loading, setLoading] = useState(false);
  const [key, setKey] = useState(Math.random());
  useEffect(() => {
    setKey(Math.random());
    setAddingDep(dep);
  }, [dep]);
  const myRef = useRef(null); // 创建 ref
  return (
    <Modal
      key={key}
      title="新增部门"
      cancelText="取消"
      okText="确定"
      destroyOnClose={true}
      open={open}
      onOk={() => {
        myRef.current.click();
      }}
      onCancel={() => {
        onCancel();
      }}
    >
      <Spin
        spinning={loading}
        tip="正在提交..."
        size="large"
        fullscreen={true}
      ></Spin>
      <Form
        onFinish={() => {
          setLoading(true);
          onOk(addingDep);
          setLoading(false);
        }}
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 14,
        }}
        layout="horizontal"
        initialValues={{
          name: "",
          explain: "",
        }}
        preserve={false}
      >
        <Form.Item
          label="名称"
          name="name"
          rules={[
            {
              required: true,
              message: "请输入部门名称",
            },
          ]}
        >
          <Input
            value={addingDep.name}
            onChange={(e) =>
              setAddingDep({ ...addingDep, name: e.target.value })
            }
          />
        </Form.Item>
        <Form.Item
          label="描述"
          name="explain"
          rules={[
            {
              required: true,
              message: "请输入部门描述",
            },
          ]}
        >
          <Input.TextArea
            rows={4}
            value={addingDep.explain}
            onChange={(e) =>
              setAddingDep({ ...addingDep, explain: e.target.value })
            }
          />
        </Form.Item>
        <Form.Item>
          <button
            type="submmit"
            ref={myRef}
            style={{ display: "none" }}
          ></button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddDepartment;
